package com.example.androidbrowserpro;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.androidTool.InstallAPKUtils;
import com.androidTool.SystemService;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Enumeration;

public class WebViewJsBridge {
    private WebViewActivity _activity;
    private WebView _webView;

    public WebViewJsBridge(WebViewActivity activity, WebView webView) {
        _activity = activity;
        _webView = webView;
    }

    //調用js
    public void callJsFun(String scriptStr) {
        //"javascript:getDataForAndroid()"
        _activity.runOnUiThread(new Runnable() {//其中 WebViewActivity 是webview所在的Activity
            public void run() {
                _webView.evaluateJavascript(scriptStr, new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        // 此处为JS返回的结果
                    }
                });
            }
        });
    }

    @JavascriptInterface
    public void hello(String msg) {
        Log.d("WebViewJsBridge", msg);
    }

    //============================================= TTS 相关==============================
    //TTS状态
    @JavascriptInterface
    public boolean ttsIsSpeak() {
        return SpeechService.getTextToSpeech().isSpeaking();
    }

    //调TTS说话
    @JavascriptInterface
    public void jsSpeak(String msg) {
        Log.d("WebViewJsBridge", msg);
        if (SpeechService.textToSpeechIsInitialized == true) {
            SpeechService.speakText(msg, new SpeechService.TTSCallback() {
                @Override
                public void over() {
                    callJsFun("javascript:ttsSpeakOver()");
                }
            });
        }
    }

    //调TTS语速
    @JavascriptInterface
    public void setSpeechRate(float rate) {
        if (SpeechService.textToSpeechIsInitialized == true) {
            SpeechService.getTextToSpeech().setSpeechRate(rate);//用来控制语速
        }
    }

    //调TTS声调
    @JavascriptInterface
    public void setPitch(float rate) {
        if (SpeechService.textToSpeechIsInitialized == true) {
            SpeechService.getTextToSpeech().setPitch(rate);//用来控制声调
        }
    }

    //================================================获得安卓信息=========================
    @RequiresApi(api = Build.VERSION_CODES.P)
    @JavascriptInterface
    public String jsGetAndroidInfo(String msg) {
        String data = MyTool.getAndroidInfoJson(_webView.getContext());
        Log.d("WebViewJsBridge", data);
        return data;
    }

    //================================================设置音量=========================
    @JavascriptInterface
    public void setAndroidVolume(int num) {
        Toast.makeText(MyApplication.getContext(),"设置声音",Toast.LENGTH_SHORT).show();
        AudioManager audioManager = (AudioManager) _activity.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, num, 0);
    }

    //=================================================设置亮度======================
    //0-255 设置系统亮度 无效，用下面的
    @JavascriptInterface
    public void setScreenBrightness(int value) {
        ContentResolver contentResolver = _activity.getContentResolver();
        try {
            int mode = Settings.System.getInt(contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE);
            if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        Settings.System.putInt(contentResolver,
                Settings.System.SCREEN_BRIGHTNESS, value);
    }

    //设置窗口亮度
    @JavascriptInterface
    public void setWindowBrightness(int brightness) {
        Toast.makeText(MyApplication.getContext(),"设置亮度",Toast.LENGTH_SHORT).show();
        _activity.runOnUiThread(new Runnable() {//其中 WebViewActivity 是webview所在的Activity
            public void run() {
                Window window = _activity.getWindow();
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.screenBrightness = brightness;// / 255.0f;
                window.setAttributes(lp);
            }
        });
    }

    //================================================清浏览器缓存=========================
    @JavascriptInterface
    public void removeAllCached() {
        Log.d("removeAllCached", "");
        _webView.clearCache(true);
    }

    //================================================重启，关机=========================
    //关机
    @JavascriptInterface
    public static void shutDown() {
        SystemService.shutDown();
    }

    //重启
    @JavascriptInterface
    public static void reBoot() {
        SystemService.reBoot();
    }

    //================================================更新程序===========================
    @JavascriptInterface
    public void downApk(String url) {
        Context mContext = MyApplication.getContext();
        InstallAPKUtils.downLoad(mContext, url, new InstallAPKUtils.Callback() {
            @Override
            public void success(String path) {
                try {
                    Toast.makeText(mContext, "恭喜你下载成功，开始安装！", Toast.LENGTH_SHORT);
                    InstallAPKUtils.installApk(mContext, path);
                } catch (Exception ex) {
                    Toast.makeText(mContext, ex.getMessage(), Toast.LENGTH_SHORT);
                }
            }
        });
    }

    //================================================设置浏览器=========================
    //设置--确定，保存新的默认URL
    @JavascriptInterface
    public void saveUrlSet(String str) {
        SharedPreferences sp = _webView.getContext().getSharedPreferences("webViewSetting", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("url", str);
        editor.apply();
        if(str.contains("?")){
            str+="&tt="+System.currentTimeMillis();
        }else{
            str+="?tt="+System.currentTimeMillis();
        }
        String finalStr = str;
        _activity.runOnUiThread(new Runnable() {//其中 WebViewActivity 是webview所在的Activity
            public void run() {
                _webView.clearCache(true);
                _webView.loadUrl(finalStr);
            }
        });
    }

    //设置--取消，打开默认URL
    @JavascriptInterface
    public void closeUrlSet() {
        SharedPreferences sp = _webView.getContext().getSharedPreferences("webViewSetting", Context.MODE_PRIVATE);
        String str = sp.getString("url", "file:///android_asset/index.html");
        Log.d(str, _webView.toString());
        if(str.contains("?")){
            str+="&tt="+System.currentTimeMillis();
        }else{
            str+="?tt="+System.currentTimeMillis();
        }
        String finalStr = str;
        _activity.runOnUiThread(new Runnable() {//其中 WebViewActivity 是webview所在的Activity
            public void run() {
                _webView.clearCache(true);
                _webView.loadUrl(finalStr);
//                _webView.goBack();
            }
        });
    }
    //获取url
    @JavascriptInterface
    public String getUrl(){
        SharedPreferences sp = _webView.getContext().getSharedPreferences("webViewSetting", Context.MODE_PRIVATE);
        String str = sp.getString("url", "http://192.168.2.37:7003/?id=d0001");
        Log.d(str, _webView.toString());
        return str;
    }

    //设置--关闭程序
    @JavascriptInterface
    public void exit() {
        _activity.stopService();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @JavascriptInterface
    public void setAutoRun(String open){
        SharedPreferences sp=MyApplication.getContext().getSharedPreferences("LocalConfig",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (!open.isEmpty()&&open.toLowerCase().contains("no")) {
            editor.putString("ISOPEN", "NO");
        }else{
            editor.putString("ISOPEN", "YES");
        }
        editor.apply();
        String tips=sp.getString("ISOPEN","xxx");
        Toast.makeText(MyApplication.getContext(),tips,Toast.LENGTH_SHORT).show();
    }

    /**
     * 设置定时开关机
     */
    @JavascriptInterface
    public void setPowerOnOff(){

        // 获取系统定时开关机服务
        AlarmManager alarmManager = (AlarmManager) MyApplication.getContext().getSystemService(Context.ALARM_SERVICE);

// 定义定时开机意图
        Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED);
        PendingIntent bootPendingIntent = PendingIntent.getBroadcast(MyApplication.getContext(), 0, bootIntent, 0);

// 定义定时关机意图
        Intent shutdownIntent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
        shutdownIntent.putExtra("android.intent.extra.KEY_CONFIRM", false);
        PendingIntent shutdownPendingIntent = PendingIntent.getBroadcast(MyApplication.getContext(), 0, shutdownIntent, 0);

// 设置定时开机时间
        Calendar bootTime = Calendar.getInstance();
        bootTime.setTimeInMillis(System.currentTimeMillis());
        bootTime.set(Calendar.HOUR_OF_DAY, 8);
        bootTime.set(Calendar.MINUTE, 11);
        bootTime.set(Calendar.SECOND, 0);

// 设置定时关机时间
        Calendar shutdownTime = Calendar.getInstance();
        shutdownTime.setTimeInMillis(System.currentTimeMillis());
        shutdownTime.set(Calendar.HOUR_OF_DAY, 8);
        shutdownTime.set(Calendar.MINUTE, 10);
        shutdownTime.set(Calendar.SECOND, 0);

// 设置定时开关机时间
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, bootTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, bootPendingIntent);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, shutdownTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, shutdownPendingIntent);


        Toast.makeText(MyApplication.getContext(),"设置定时开关机",Toast.LENGTH_SHORT).show();
//        以上代码中，我们首先获取系统定时开关机服务 AlarmManager 的实例。然后，我们定义了两个意图 bootIntent 和 shutdownIntent，用于定时开机和定时关机。接下来，我们使用 PendingIntent.getBroadcast() 方法创建延迟意图，并将这些意图传递给 AlarmManager.setRepeating() 方法，以设置定时开关机时间。在这个示例中，我们将定时开机时间设置为每天早上8点30分，将定时关机时间设置为每天下午6点，但您可以根据需要自定义时间。
//
//        需要注意的是，为了能够执行这些操作，需要在应用程序的清单文件中声明适当的权限。例如，如果您要执行定时关机操作，则需要声明 android.permission.SHUTDOWN 权限。此外，这些操作还需要系统签名级别的权限才能执行。

//        boolean boo=SystemService.setPowerOnOff();
//        if(boo){
//            Toast.makeText(MyApplication.getContext(),"设置定时开关机成功",Toast.LENGTH_SHORT).show();
//        }else{
//            Toast.makeText(MyApplication.getContext(),"设置定时开关机失败",Toast.LENGTH_SHORT).show();
//        }
//        //获取系统的日期
////年
//        Calendar calendar = Calendar.getInstance();
//        int year = calendar.get(Calendar.YEAR);
////月
//        int month = calendar.get(Calendar.MONTH)+1;
////日
//        int day = calendar.get(Calendar.DAY_OF_MONTH);
////获取系统时间
////小时
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
////分钟
//        int minute = calendar.get(Calendar.MINUTE);
////秒
//        int second = calendar.get(Calendar.SECOND);
//        int [] timeonArray = new int[]{hour,minute+1};
//        int [] timeoffArray = new int[]{hour,minute+3};
//        int[] weekdays = new int[]{1,1,1,1,1,1,1};//周一到周日工作状态,1为开机，0为不开机
//        String v=MyApplication.manager.getVersion();
//        Toast.makeText(MyApplication.getContext(),v,Toast.LENGTH_SHORT);
//        boolean boo= MyApplication.manager.setPowerOnOffWithWeekly(timeonArray,timeoffArray,weekdays);
//        if(boo){
//            Toast.makeText(MyApplication.getContext(),"设置定时开关机成功",Toast.LENGTH_LONG).show();
//        }else{
//            Toast.makeText(MyApplication.getContext(),"设置定时开关机失败",Toast.LENGTH_LONG).show();
//        }
    }

    @JavascriptInterface
    public String getIp(){
            try {
                Toast.makeText(MyApplication.getContext(),"获取IP",Toast.LENGTH_SHORT).show();
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                    {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address))
                        {
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            }
            catch (SocketException ex){
                ex.printStackTrace();
            }
            return null;
        }

    @JavascriptInterface
    public  void lockNow(int ms) {
//        boolean admin = _activity.policyManager.isAdminActive( _activity.adminReceiver);
//        if (admin) {
//            _activity.policyManager.lockNow();
//            //handler.sendEmptyMessageDelayed(1, 3000);
//        } else {
//            Toast.makeText(_activity, "没有设备管理权限",
//                    Toast.LENGTH_LONG).show();
//        }
    }


    @SuppressLint("InvalidWakeLockTag")
    public void turnOnScreen() {
//        // turn on screen
//        Log.v("ProximityActivity", "ON!");
//        PowerManager.WakeLock mWakeLock =_activity.mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
//        mWakeLock.acquire();
//        mWakeLock.release();
    }

    @JavascriptInterface
    public void turnOnScreen1() {
        this.turnOnScreen();
    }

    @JavascriptInterface
    public void restartApp() {
        try{
            new Http().getHttpURLConnection("心跳返回异常,重启 APP");
            Intent intent = new Intent(MyApplication.getContext(), RestartService.class);
            MyApplication.getContext().startService(intent);
            _activity.finish();
        }catch (Exception ex){
            new Http().getHttpURLConnection(ex.getMessage());
        }
    }
}